﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KCurveAPI
{
  public delegate int GetStockQuote(StockQuote sq);

  public class KCurve
  {
    public const int MAX_LEN = 255;
    GetStockQuote m_method;
    public KCurve(GetStockQuote method)
    {
      m_method = method;
    }

    public int GetQuoteTimeInfo(out DateTime QuoteStartTime, out DateTime PauseStartTime, out DateTime PauseEndTime, out DateTime QuoteEndTime)
    {
      byte[] qst = new byte[MAX_LEN];
      byte[] pst = new byte[MAX_LEN];
      byte[] pet = new byte[MAX_LEN];
      byte[] qet = new byte[MAX_LEN];
      CFHAPIInvoke.GetQuoteTimeInfo(qst, pst, pet, qet);

      QuoteStartTime = DateTime.Parse(ArrCharToString(qst));
      PauseStartTime = DateTime.Parse(ArrCharToString(pst));
      PauseEndTime = DateTime.Parse(ArrCharToString(pet));
      QuoteEndTime = DateTime.Parse(ArrCharToString(qet));

      return 0;
    }

    public void work()
    {
      while (true)
      {
        IStruct sq = new IStruct();
        CFHAPIInvoke.GetStockQuote(ref sq);

        StockQuote csq = new StockQuote();

        // convert sq to csq
        ConvertSQtoCSQ(sq, csq);

        // 回调至宿主
        m_method(csq);
      }
    }

    public void ConvertSQtoCSQ(IStruct sq, StockQuote csq)
    {
      csq.Windcode = ArrCharToString(sq.Windcode);
      csq.ShortName = ArrCharToString(sq.ShortName);
      csq.CurrentDate = ArrCharToString(sq.CurrentDate);
      csq.CurrentPrice = ArrCharToString(sq.CurrentPrice);
      csq.Swing = ArrCharToString(sq.Swing);
      csq.SwingPercent = ArrCharToString(sq.SwingPercent);
      csq.IsDown = sq.IsDown == 1 ? true : false;
      csq.YestodayPrice = sq.YestodayPrice;
    }

    public string ArrCharToString(byte[] src)
    {
      string des = Encoding.Default.GetString(src);
      des = des.Trim('\0');
      return des;
    }
  }
}
